<?php
require_once('PHPUnit/Extensions/Database/TestCase.php');
require_once('./includes/phpunit_setup.inc');

require_once('database.fnsql.inc');
class database_fnsql_inc_Test extends DrupalTddTestCase {
  public function setup() {
    parent::setup();
    $this->table = 'node';
    module_enable(array('devel'));
  }
  
  public function teardown() {
    db_query('TRUNCATE %s', $this->table);
  }
  
  public function testSetTableReturnsTablename() {
    $db = new KDatabase();
    $table = $db->SetTable($this->table);    
    $this->assertEquals($this->table, $table);
    
    $newdb = new KDatabase('revisions');
    $this->assertEquals('revisions', $newdb->GetTable());
  }
  public function testInsertRowReturnsTrueAndSetsPrimaryKey() {
    $row = array('title' => 'DBTest Title');
    $db = new KDatabase($this->table);
    $status = $db->InsertRow($row);    
    $this->assertEquals(SAVED_NEW, $status, 'Failed to insert row into database');
    $this->assertTrue(isset($row->nid), 'Primary key, nid, was not set');
  }
  
  public function testRetrieveRowWithKeyReturnsInsertedRow() {
    $row = array('title' => 'DBTest Title');
    $db = new KDatabase('node');  
    $status = $db->InsertRow($row);
    $this->assertEquals(SAVED_NEW, $status, 'Failed to insert row into database');
    $key = array(sprintf('nid=%d', $row->nid));
    $rr = $db->RetrieveRow(array('wheres' => $key));    
    $this->assertEquals($row->title, $rr->title,
                        'Retrieved row not equal to inserted row');
    $rows = $db->RetrieveRows();
    $this->assertEquals(1, count($rows), 'One row expected in table');
    $rows = $db->RetrieveRows(array('limit' => 1));
    $this->assertEquals(1, count($rows), 'One row expected in table');
    $rows = $db->RetrieveRows(array('limit' => '1'));
    $this->assertEquals(1, count($rows), 'One row expected in table');
    $rows = $db->RetrieveRows(array('limit' => '0,1'));
    $this->assertEquals(1, count($rows), 'One row starting from row 0');
    $rows = $db->RetrieveRows(array('limit' => '1,1'));
    $this->assertEquals(0, count($rows), 'No row after row 1');
  }
  
  public function testUpdateRow() {
    $row = array('title' => 'Title');
    $db = new KDatabase($this->table);
    $db->InsertRow($row);
    $key = array(sprintf('nid=%d', $row->nid));
    $newTitle = 'New Title';
    $row->title = $newTitle;
    $db->UpdateRow($row);
    $rr = $db->RetrieveRow(array('wheres' => $key));    
    $this->assertEquals($newTitle, $rr->title, 'Update of row failed');
  }

}

